// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RobotPoseEstimationModelAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Navigation.Visualization.GroundTruthExtraction
{
    using System;
    using System.Runtime.Serialization;

    using Microsoft.Robotics.Navigation.Runtime.GroundTruthExtraction;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Vision;
    using Microsoft.Robotics.Vision.Cameras;
    using Microsoft.Robotics.Vision.Runtime.Cameras;
    using Microsoft.Robotics.Vision.Visualization;    
    using Microsoft.Robotics.Visualization;    

    /// <summary>
    /// This model agent class prepares the Ground Truth frame for visualization.
    /// </summary>
    [DataContract]
    public sealed class RobotPoseEstimationModelAgent : ModelAgent<RGBCameraAgentMessage, RobotPoseEstimationModel>,
        ISubscriptionReceiver<RobotPoseEstimationAgentMessage>
    {
        /// <summary>
        /// Name of the agent producing the robot pose estimation agent message to subscribe to
        /// </summary>
        [DataMember(Name = "RobotPoseEstimationMessageProducer")]
        private string groundTruthExtractionMessageProducer;

        /// <summary>
        /// Select the type of display
        /// </summary>
        [DataMember(Name = "ImageFormat")]
        private SimplePixelFormat? imageFormat;

        /// <summary>
        /// RobotPoseEstimationMessageProducerAgent we are subscribed to.
        /// </summary>
        private IAgentHost robotPoseEstimationMessageProducerAgent;

        /// <summary>
        /// Initializes a new instance of the RobotPoseEstimationModelAgent class        
        /// </summary>
        /// <param name="name">Agent name</param>
        /// <param name="rgbImageProducer">The RGB image producer.</param>
        /// <param name="robotPoseProducer">The robot pose estimation producer.</param>
        /// <param name="maxUpdateIntervalMilliseconds">The interval on which to issue data binding updates to the UI</param>
        /// <param name="imageFormat">Image format</param>
        public RobotPoseEstimationModelAgent(
            string name,
            IProducer<RGBCameraAgentMessage> rgbImageProducer,
            IProducer<RobotPoseEstimationAgentMessage> robotPoseProducer,
            int maxUpdateIntervalMilliseconds,
            SimplePixelFormat imageFormat)
            : base(name, rgbImageProducer.Name, maxUpdateIntervalMilliseconds)
        {
            this.imageFormat = (SimplePixelFormat)imageFormat;
            this.groundTruthExtractionMessageProducer = robotPoseProducer.Name;
        }

        /// <summary>
        /// Initializes any fields not provided in the manifest.
        /// </summary>
        /// <param name="locator">Not used.</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
         
            if (this.imageFormat == null)
            {
                this.imageFormat = SimplePixelFormat.Gray8;
            }

            if (this.groundTruthExtractionMessageProducer != default(string))
            {
                this.robotPoseEstimationMessageProducerAgent = this.Locator.GetAgent(this.groundTruthExtractionMessageProducer);
                this.robotPoseEstimationMessageProducerAgent.Subscribe<RobotPoseEstimationAgentMessage>(this);
            }
        }

        /// <summary>
        /// Process robot pose estimation message and update the UI
        /// </summary>
        /// <param name="message">Robot pose estimation message</param>
        public void Receive(RobotPoseEstimationAgentMessage message)
        {
            string robotXAbsolute = string.Empty;
            string robotYAbsolute = string.Empty;
            string robotHeadingAbsolute = string.Empty;

            string robotXRelative = string.Empty;
            string robotYRelative = string.Empty;
            string robotHeadingRelative = string.Empty;
            if (message.RobotPose != null)
            {
                if (message.Landmark != null)
                {
                    robotXAbsolute = (message.RobotPose.Value.X * MathConstants.MilliunitsPerUnit).ToString("F2");
                    robotYAbsolute = (message.RobotPose.Value.Y * MathConstants.MilliunitsPerUnit).ToString("F2");
                    robotHeadingAbsolute = (message.RobotPose.Value.Heading * MathConstants.Radians2Degrees).ToString("F2");
                    robotXRelative = ((message.RobotPose.Value.X - message.Landmark.Pose.X) * MathConstants.MilliunitsPerUnit).ToString("F2");
                    robotYRelative = ((message.RobotPose.Value.Y - message.Landmark.Pose.Y) * MathConstants.MilliunitsPerUnit).ToString("F2");
                    robotHeadingRelative = ((message.RobotPose.Value.Heading - message.Landmark.Pose.Heading) * MathConstants.Radians2Degrees).ToString("F2");
                }
                else
                {
                    robotXRelative = ((message.RobotPose.Value.X) * MathConstants.MilliunitsPerUnit).ToString("F2");
                    robotYRelative = ((message.RobotPose.Value.Y) * MathConstants.MilliunitsPerUnit).ToString("F2");
                    robotHeadingRelative = ((message.RobotPose.Value.Heading) * MathConstants.Radians2Degrees).ToString("F2");
                }
            }

            this.Model.RobotPoseAbsolute = string.Format(
               "Robot Absolute X = {0}, Y = {1}, Heading = {2}",
               robotXAbsolute,
               robotYAbsolute,
               robotHeadingAbsolute);

            this.Model.RobotPoseRelative = string.Format(
               "Robot Landmark Relative X = {0}, Y = {1}, Heading = {2}",
               robotXRelative,
               robotYRelative,
               robotHeadingRelative);

            string landmarkId = string.Empty;
            string landmarkX = string.Empty;
            string landmarkY = string.Empty;
            string landmarkHeading = string.Empty;

            if (message.Landmark != null)
            {
                landmarkId = (message.Landmark.Id).ToString("F2");
                landmarkX = (message.Landmark.Pose.X * MathConstants.MilliunitsPerUnit).ToString("F2");
                landmarkY = (message.Landmark.Pose.Y * MathConstants.MilliunitsPerUnit).ToString("F2");
                landmarkHeading = (message.Landmark.Pose.Heading * MathConstants.Radians2Degrees).ToString("F2");
            }

            this.Model.Landmark =
                string.Format(
                "Landmark Id = {0} X = {1} Y = {2} Heading = {3}",
                landmarkId,
                landmarkX,
                landmarkY,
                landmarkHeading);
        }

        /// <summary>
        /// Updates the model data with the new state.
        /// </summary>
        /// <param name="state">The new state from the upstream agent.</param>
        /// <returns>true if the model was updated, false otherwise</returns>
        protected unsafe override bool UpdateModel(RGBCameraAgentMessage state)
        {
            ImageFrameGray8 grayImage = ImageOperations2DInterop.ConvertYUY2ToGray8Image(state.RGBImageFrame);

            System.Drawing.Size lumSize = new System.Drawing.Size(state.RGBImageFrame.Width, state.RGBImageFrame.Height);            

            if (this.imageFormat == SimplePixelFormat.Gray8)
            {
                this.Model.VideoFrame = new VideoFrame()
                {
                    Data = grayImage.ImageData,
                    Size = lumSize,
                    Format = SimplePixelFormat.Gray8,
                    Stride = state.RGBImageFrame.Width
                };
            }
            else
            {
                throw new Exception("RGBCamera - unsupported image type " + this.imageFormat.ToString());
            }

            return true;
        }
    }
}
